package org.os.framework.context.config;

import org.os.framework.crypto.algorithm.Aes;
import org.os.framework.crypto.algorithm.Rsa;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 安全响应
 * @author
 */
@Slf4j
@Data
@Order(0)
@ConfigurationProperties(prefix = "spring.webmvc.security")
@Configuration
public class SecurityConfig {

    private static Rsa rsa = null;

    /**
     * 私钥
     */
    private String privateKey = "";

    /**
     * 公钥
     */
    private String publicKey = "";

    /**
     * 密码
     */
    private String password;

    /**
     * 是否开启加密
     */
    private Boolean encrypt = false;

    /**
     * 是否开启解密
     */
    private Boolean decrypt = false;

    private Rsa rsa() {
        if (SecurityConfig.rsa == null) {
            log.info("security = {}", this);
            if (StringUtils.hasText(password)) {
                Aes aes = Aes.builder()
                        .password(password)
                        .build();
                privateKey = aes.decrypt(privateKey);
            }
            SecurityConfig.rsa = Rsa.builder()
                    .privateKey(privateKey)
                    .publicKey(publicKey)
                    .build();
        }
        return SecurityConfig.rsa;
    }

    public String encrypt(String original) {
        return this.rsa().encrypt(original);
    }

    public String decrypt(String encrypted) {
        return this.rsa().decrypt(encrypted);
    }

}
